<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\AdminUserCreateRequest;
use App\Http\Requests\Admin\AdminUserUpdateRequest;
use App\Models\Admin\AdminUser;
use App\Models\Admin\Group;
use App\Models\Admin\Permission;
use App\Models\Admin\Role;
use App\Models\Inventory\Area;
use App\Models\Inventory\BatchImportUserHistory;
use App\Models\Inventory\BusinessHall;
use App\Repositories\Admin\AdminUserRepository;
use Auth;
use DB;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Tab;
use Excel;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Response;
//校验
use Validator;

set_time_limit(0);
// 设置内存限制大小,php.ini中设置的是128M
// ini_set('memory_limit', '256M');

class UserController extends Controller
{
    use ModelForm;

    /** @var  userRepository */
    private $userRepository;

    /**
     * [$route_prefix 读取配置的路由前缀]
     * @var [type]
     */
    protected $route_prefix;

    protected $fields = [
        'groups'         => [],
        'roles'          => [],
        'permissions'    => [],
        'groupsAll'      => [],
        'rolesAll'       => [],
        'permissionsAll' => [],
    ];

    /**
     * [__construct 构造函数]
     * @param AdminUserRepository $userRepo [description]
     */
    public function __construct(AdminUserRepository $userRepo)
    {
        $this->userRepository = $userRepo;
        $this->route_prefix   = config('inventory.base.route_prefix') ? config('inventory.base.route_prefix') : 'admin';
    }

    /**
     * [generateTree 递归生成树]
     * @param  [type]  $cate  [description]
     * @param  string  $name  [description]
     * @param  integer $f_pid [description]
     * @return [type]         [description]
     */
    public function generateTree($cate, $name = 'child', $f_pid = 0)
    {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['f_pid'] == $f_pid) {
                $v[$name] = self::generateTree($cate, $name, $v['id']);
                $arr[]    = $v;
            }
        }
        return $arr;
    }

    /**
     * Display a listing of the user.
     *
     * @param userDataTable $userDataTable
     * @return Response
     */
    public function index()
    {
        // 判断是否有列表权限
        if (!\Gate::check('admin.user.index')) {
            return response()->view(config('inventory.base.no_permisson'));
        }
        return Admin::content(function (Content $content) {
            $content->header(__('inventory.user.index_header'));
            $content->description(__('inventory.user.index_description'));
            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new user.
     *
     * @return Response
     */
    public function create()
    {
        // 判断是否有修改权限
        if (!\Gate::check('admin.user.create')) {
            return response()->view(config('inventory.base.no_permisson'));
        }

        return Admin::content(function (Content $content) {

            $content->header(__('inventory.user.create_header'));
            $content->description(__('inventory.user.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created user in storage.
     *
     * @param AdminUserCreateRequest $request
     *
     * @return Response
     */
    public function store(AdminUserCreateRequest $request)
    {
        // 判断是否有修改权限
        if (!\Gate::check('admin.user.create')) {
            return response()->view(config('inventory.base.no_permisson'));
        }

        $input = $request->all();

        $user = $this->userRepository->create($input);

        // 新建用户, 记录日志
        event(new \App\Events\OperationUserEvent('\App\Models\Admin\AdminUser', $user, '新建用户', json_encode($input)));

        Flash::success(__('inventory.user.message_saved'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route($this->route_prefix . '.user.index'));
    }

    /**
     * Display the specified user.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        // $user = $this->userRepository->findWithoutFail($id);

        // if (empty($user)) {
        //     Flash::error(__('inventory.user.message_not_found'));

        //     return redirect(route($this->route_prefix . '.user.index'));
        // }

        // return view('inventory.user.show')->with('user', $user);
    }

    /**
     * Show the form for editing the specified user.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        // 判断是否有修改权限
        if (!\Gate::check('admin.user.edit')) {
            return response()->view(config('inventory.base.no_permisson'));
        }
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('inventory.user.edit_header'));
            $content->description(__('inventory.user.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * 【因为tab的时候存的数据可以根据tab分别存, 所以update的时候不走自己的方法】
     * Update the specified user in storage.
     *
     * @param  int              $id
     * @param AdminUserUpdateRequest $request
     *
     * @return Response
     */
    // public function update($id, AdminUserUpdateRequest $request)
    // {
    //     // 判断是否有修改权限
    //     // if (!\Gate::check('admin.user.edit')) {
    //     //     return response()->view(config('inventory.base.no_permisson'));
    //     // }

    //     $user = $this->userRepository->findWithoutFail($id);

    //     if (empty($user)) {
    //         Flash::error(__('inventory.user.message_not_found'));

    //         return redirect(route($this->route_prefix . '.user.index'));
    //     }

    //     $user = $this->userRepository->update($request->all(), $id);

    //     Flash::success(__('inventory.user.message_updated'));

    //     return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route($this->route_prefix . '.user.index'));
    //     // return redirect(route($this->route_prefix . '.user.index'));
    // }

    /**
     * Remove the specified user from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {

        //判断是否有删除权限
        // if (!\Gate::check('admin.user.destroy')) {
        //     return response()->view(config('inventory.base.no_permisson'));
        // }

        // 根据,判断传递过来的是单个id还是多个id(string)
        $ids = explode(",", $id);

        // 因为用户和角色组, 角色, 权限有关所以不能单纯的用批量删除
        foreach ($ids as $key => $id) {
            $user = $this->userRepository->findWithoutFail($id);

            if (empty($user)) {
                Flash::error(__('inventory.user.message_not_found'));

                return redirect(route($this->route_prefix . '.user.index'));
            }

            // 删除用户, 记录日志
            event(new \App\Events\OperationUserEvent('\App\Models\Admin\AdminUser', $user, '删除用户', $id));

            if ($flag = $this->userRepository->delete($id)) {
                $user->groups()->detach();
                $user->roles()->detach();
                $user->permissions()->detach();
            } else {
                return response()->json(['message' => __('inventory.message_delete_error'), 'status' => $flag]);
            }
        }
        return response()->json(['message' => __('inventory.user.message_deleted'), 'status' => $flag]);
    }

    /**
     * [distributionView 分配权限视图]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function distributionView($id)
    {
        //判断是否有该用户
        $user = AdminUser::find($id);
        if (!$user) {
            return redirect('/admin/user')->withErrors("找不到该用户!");
        }

        //该用户有的【角色组】
        $groups         = $user->groups->pluck('id')->toArray();
        $data['groups'] = $groups;

        // 超级管理员看到的是所有【角色组】
        if (Auth::guard(config('inventory.base.guard'))->user()->level == 1) {
            $data['groupsAll'] = Group::all()->toArray();
        } else {
            //分配人的角色组
            $arrTempGroups     = Auth::guard(config('inventory.base.guard'))->user()->groups->pluck('id')->toArray();
            $data['groupsAll'] = Group::all()->whereIn('id', $arrTempGroups)->toArray();
        }

        //该用户有的【角色】
        $roles         = $user->roles->pluck('id')->toArray();
        $data['roles'] = $roles;
        // 超级管理员看到的是所有【角色】
        if (Auth::guard(config('inventory.base.guard'))->user()->level == 1) {
            $data['rolesAll'] = Role::all()->toArray();
        } else {
            /**
             * 角色列表应该来自用户有的角色 和 用户有的角色组
             */
            //分配人的角色
            $arrTempRoles = Auth::guard(config('inventory.base.guard'))->user()->roles->pluck('id')->toArray();
            //分配人的角色组
            $arrTempGroups = Auth::guard(config('inventory.base.guard'))->user()->groups->pluck('id')->toArray();
            $arrGroupRoles = Role::whereHas('groups', function ($query) use ($arrTempGroups) {
                $query->whereIn('group_id', $arrTempGroups);
            })->pluck('id')->toArray();

            // array_unique(array_merge_recursive($arrGroupRoles, $arrTempRoles));
            $data['rolesAll'] = Role::all()->whereIn('id', array_unique(array_merge_recursive($arrGroupRoles, $arrTempRoles)))->toArray();
        }

        //该用户有的权限 和 所有权限
        $permissions         = $user->permissions->pluck('id')->toArray();
        $data['permissions'] = $permissions;

        //取出所有的菜单【然后根据listorder进行升序排序】
        $menu        = \App\Models\Admin\Menu::orderBy('listorder', 'asc')->get()->toArray();
        $menu        = $this->generateTree($menu);
        $permissions = Permission::all()->toArray();

        //遍历一级菜单
        foreach ($menu as $k => $v) {
            //遍历二级菜单
            foreach ($v['child'] as $key => $value) {
                //二级菜单的id
                $secondMenuId = $value['id'];
                //通过二级菜单的id找出二级菜单下的权限
                $menu[$k]['child'][$key]['child'] = array_filter($permissions, function ($permission) use ($secondMenuId) {
                    if ($permission['f_pid'] == $secondMenuId) {
                        return \Gate::check($permission['name']);
                    }
                    return false;
                });
                //如果二级的子级没有则删除
                if (count($menu[$k]['child'][$key]['child']) == 0) {
                    unset($menu[$k]['child'][$key]);
                }
            }
            //如果顶级的子级则要删除
            if (count($menu[$k]['child']) == 0) {
                unset($menu[$k]);
            }
        }
        $data['permissionsAll'] = $menu;
        $data['id']             = $id;

        return view('admin.user.edit', $data);
    }

    /**
     * [distribution 保存分配的权限-自己加的]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function distribution($id, Request $request)
    {
        $user = AdminUser::find($id);
        if (empty($user)) {
            Flash::error(__('inventory.user.message_not_found'));

            return redirect(route($this->route_prefix . '.user.index'));
        }

        $user->groups()->sync($request->input('groups', []));
        $user->roles()->sync($request->input('roles', []));
        $user->permissions()->sync($request->input('permissions', []));

        // 修改权限, 记录日志
        event(new \App\Events\OperationUserEvent('\App\Models\Admin\AdminUser', $user, '修改权限', json_encode(['group' => $request->input('groups', []), 'roles' => $request->input('roles', []), 'permissions' => $request->input('permissions', [])])));

        Flash::success(__('inventory.user.message_distribution'));

        return redirect(route($this->route_prefix . '.user.index'));
        // return redirect('/admin/user')->withSuccess('添加成功！');
    }

    /**
     * 批量导入用户-视图
     * @param Request $request
     */
    public function batchImportView()
    {
        return Admin::content(function (Content $content) {
            $content->header(__('inventory.user.batch_import_header'));
            $content->description(__('inventory.user.batch_import_description'));

            $box = new Box('模板说明', '<p>用户的模板需要的字段:<b>name</b>(账号, 必须), <b>real_name</b>(真实姓名, 必须), <b>password</b>(密码, 可选。默认:"123456"), <b>phone</b>(手机号, 必须), <b>cityname, cells</b>(账号可以看见的地区范围, 需要和地区管理里面的名字相符。如何两个字段都有值则用cells。), <b>restore</b>(营业厅的名称, 营业厅的名称需要和营业厅管理里面的营业厅名称一致。必须), <b>role</b>(角色名, 需要和角色管理里面的角色名一致。必须), <b>wxno</b>(微信openid, 可选)<a href="/upload/batch_import_template/user_sample.xlsx" class="btn btn-warning"><i class="fa fa-download"></i>下载模板</a></p>');
            $content->row($box->style('primary'));

            $content->body($this->batchImportForm());
        });
    }

    /**
     * 批量导入用户
     * [batchImport description]
     * @return [type] [description]
     */
    public function batchImport(Request $request)
    {
        //方式1上传文件:
        // $file = Input::file('file');
        // $file = $request->file('file');
        // if ($file->isValid()) {
        //     // 获取文件相关信息
        //     $originalName = $file->getClientOriginalName(); // 文件原名
        //     $ext = $file->getClientOriginalExtension();     // 扩展名
        //     $realPath = $file->getRealPath();   //临时文件的绝对路径
        //     $type = $file->getClientMimeType();     // image/jpeg
        //     // 上传文件
        //     $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
        //     // 使用我们新建的uploads本地存储空间（目录）
        //     $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));

        // }

        //定义校验, 没有移到request
        $validator = Validator::make($request->all(), [
            'file' => 'required', //|mimes:xls,csv,xlsx
        ], [
            'required' => ':attribute 未上传',
            //'mimes' => '文件格式只能为 :attribute',
        ], [
            'file' => '文件',
        ]);
        // 校验
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        //方式2上传文件:
        $file = $request->file('file');

        // 文件是否上传成功
        if ($file->isValid()) {
            //允许上传的文件格式
            $allowed_extensions = ["xls", "xlsx", "csv"]; //xlsm
            $entension          = $file->getClientOriginalExtension(); //上传文件的后缀, 扩展名
            if ($entension && !in_array($entension, $allowed_extensions)) {
                Flash::error('文件格式只能为xls, xlsx, csv');
                return back()->withInput(); //关联持久用户提交的信息
            }
            //获取文件尺寸
            $size          = $file->getSize();
            $file_max_size = config('inventory.base.file_max_size'); //文件最大限制, 现在是10M
            // $size = round($file->getSize() / 1024 / 1024);
            if ($size > $file_max_size) {
                Flash::error('文件最大只能10M');
                return back()->withInput(); //关联持久用户提交的信息
            }

            $originalName = $file->getClientOriginalName(); // 文件原名
            $type         = $file->getClientMimeType(); // image/jpeg
            $realPath     = $file->getRealPath(); //临时文件的绝对路径
            $fileName     = date('YmdHis') . '-' . uniqid();
            $newName      = $fileName . '.' . $entension; //'xls';
            // 文件上传的根路径
            $rootDir     = config('filesystems.disks.admin.root');
            $path        = $file->move($rootDir . '/import_user', $newName);
            $cretae_path = $rootDir . '/import_user/' . $newName;
            //保存日志时文件路径
            $file_url = '/import_user/' . $newName;
            $history  = [];
            $user_id  = Auth::guard(config('inventory.base.guard'))->user()->id;

            //错误的行
            $errorRow['name_empty']             = []; //账号非空
            $errorRow['name_unique']            = []; //账号唯一
            $errorRow['real_name_empty']        = []; //真实姓名非空
            $errorRow['password_empty']         = []; //密码非空
            $errorRow['area_empty']             = []; //地区非空
            $errorRow['area_validity']          = []; //地区合法性
            $errorRow['phone_empty']            = []; //手机号非空
            $errorRow['phone_unique']           = []; //手机号唯一
            $errorRow['business_hall_empty']    = []; //营业厅不能为空
            $errorRow['business_hall_validity'] = []; //营业厅合法性
            $errorRow['role_empty']             = []; //角色不能为空
            $errorRow['role_validity']          = []; //角色是否合法性
            //成功的行数
            $successCount = 0;
            //总行数
            $rowsCount = 0;
            //导入开始时间
            $starttime = microtime(true);
            // 选中第一个Sheet, 这样第一行当做属性名
            Excel::selectSheetsByIndex(0)->load($cretae_path, function ($reader) use (&$errorRow, &$successCount, &$rowsCount, &$history) {
                //获得所有数据
                $data = $reader->all()->toArray();
                //总记录数
                $num = count($data);
                //总记录数
                $rowsCount = $num;
                //第几行开始算
                $rowNo = 2;
                //批次自动生成
                $batch = date('YmdHis');

                // //判断地区是否合法【已经改为直接去查表】
                // $areas = [];
                // $areas = Area::pluck('f_id')->toArray();
                // //获得所有地区
                // $tempAreas = Area::pluck('alias', 'f_id')->toArray();

                // //判断营业厅的合法性【已经改为直接去查表】
                // $businessHalls = [];
                // $businessHalls = DB::table('business_halls')->select('area_id', 'name', 'id')->get()->toArray();

                //判断角色是否合法 - 营业员、装维人员、仓库人员
                $roles = [];
                $roles = DB::table('admin_roles')->pluck('id')->toArray();
                //获得所有的角色
                $tempRoles = DB::table('admin_roles')->pluck('name', 'id')->toArray();

                for ($i = 0; $i < $num; $i++) {
                    //判断该条记录有没有问题
                    $flag = true;
                    // 微信号-目前没用
                    $wxno = '';
                    // 用户名
                    $name = '';
                    // 真实姓名
                    $real_name = '';
                    // 密码
                    $password = '';
                    // 用户的区域属性
                    $area_id = '';
                    // 手机号
                    $phone = '';
                    // 用户的营业厅属性
                    $business_hall_id = '';
                    // 用户的角色
                    $role = '';
                    // 地市-查营业厅用
                    $city_id = '';
                    // 区县-查营业厅用
                    $district_id = '';

                    // real_name【真实姓名】不能为空
                    if (isset($data[$i]['real_name'])) {
                        $real_name = trim($data[$i]['real_name']);
                    }
                    if (empty($real_name)) {
                        $flag                          = false;
                        $errorRow['real_name_empty'][] = ($i + $rowNo);
                    }

                    // password【密码】如果为空则给默认值:123456
                    if (isset($data[$i]['password'])) {
                        $password = trim($data[$i]['password']);
                    }
                    if (empty($password)) {
                        $password = '123456';
                    }

                    // 微信的openid
                    if (isset($data[$i]['wxno'])) {
                        $wxno = trim($data[$i]['wxno']);
                    }

                    //地区不能为空 和 地区要合法
                    if (isset($data[$i]['cityname'])) {
                        $area_id = trim($data[$i]['cityname']);
                    }
                    if (isset($data[$i]['cells'])) {
                        if (!empty(trim($data[$i]['cells']))) {
                            $area_id = trim($data[$i]['cells']);
                        }
                    }
                    //地区合法性
                    if (empty($area_id)) {
                        $flag                     = false;
                        $errorRow['area_empty'][] = ($i + $rowNo);
                    } else {
                        // 判断地区是否合法,如果地区合法则将地区的中文名转为f_id
                        $area = Area::where('alias', 'like', $area_id . '%')->first();
                        if ($area) {
                            $area_id = $area->f_id;
                            if ($area->area_level_id == '01.01.01') {
                                // 如果是市
                                $city_id = $area->f_id;
                            } else if ($area->area_level_id == '01.01.01.01') {
                                // 如果是县
                                $district_id = $area->f_id;
                                $city_id     = $area->f_pid;
                            } else {
                                // 如果是国家
                                // 如果是省
                                $flag                        = false;
                                $errorRow['area_validity'][] = ($i + $rowNo);
                            }
                        } else {
                            $flag                        = false;
                            $errorRow['area_validity'][] = ($i + $rowNo);
                        }
                    }

                    //手机号不能为空 和 手机号要唯一
                    if (isset($data[$i]['phone'])) {
                        $phone = trim($data[$i]['phone']);
                    }
                    if (empty($phone)) {
                        $flag                      = false;
                        $errorRow['phone_empty'][] = ($i + $rowNo);
                    } else {
                        if (AdminUser::where('phone', '=', $phone)->first()) {
                            $flag                       = false;
                            $errorRow['phone_unique'][] = ($i + $rowNo);
                        }
                    }

                    //用户名如果为空则将手机号给用户名
                    if (isset($data[$i]['name'])) {
                        $name = trim($data[$i]['name']);
                    }
                    if (empty($name)) {
                        $name = $phone;
                    }

                    //营业厅不能为空 和 营业厅要合法
                    $business_hall_flag = false;
                    if (isset($data[$i]['restore'])) {
                        $business_hall_id = trim($data[$i]['restore']);
                    }

                    // 【后来改为营业厅可以为空】
                    // if (empty($business_hall_id)) {
                    //     $flag                              = false;
                    //     $errorRow['business_hall_empty'][] = ($i + $rowNo);
                    // }

                    // 营业厅不为空的话
                    if (!empty($business_hall_id)) {
                        // 营业厅名字 和 营业厅所属的地区要一致,并且营业厅中文转为id
                        if ($businessHall = BusinessHall::where(['city_id' => $city_id, 'district_id' => $district_id, 'name' => $business_hall_id])->first()) {
                            $business_hall_id   = $businessHall->id;
                            $business_hall_flag = true;
                        }

                        // foreach ($businessHalls as $business_hall_value) {
                        //     //营业厅名字 和 营业厅所属的地区要一致
                        //     if ($business_hall_id == $business_hall_value->name && $business_hall_value->area_id == $area_id) {
                        //         $business_hall_id   = $business_hall_value->id;
                        //         $business_hall_flag = true;
                        //         break;
                        //     }
                        // }
                    }
                    // 营业厅是否合法【需要排除当营业厅不为空的时候】
                    if (!$business_hall_flag && !empty($business_hall_id)) {
                        $flag                                 = false;
                        $errorRow['business_hall_validity'][] = ($i + $rowNo);
                    }

                    // 角色不能为空 和 需要判断角色的合法性
                    if (isset($data[$i]['role'])) {
                        $role = trim($data[$i]['role']);
                    }
                    if (empty($role)) {
                        $flag                     = false;
                        $errorRow['role_empty'][] = ($i + $rowNo);
                    } else {
                        foreach ($tempRoles as $id => $rolename) {
                            if (!(strpos($rolename, $role) === false)) {
                                $role = $id;
                                break;
                            }
                        }
                        if (!in_array($role, $roles)) {
                            $flag                        = false;
                            $errorRow['role_validity'][] = ($i + $rowNo);
                        }
                    }

                    //角色要通过关联插入进去
                    if ($flag) {
                        //new一个用户
                        $adminUser = new AdminUser;
                        //目前可以为空-微信的openid
                        $adminUser->wxno             = $wxno;
                        $adminUser->name             = $name;
                        $adminUser->real_name        = $real_name;
                        $adminUser->password         = $password;
                        $adminUser->area_id          = $area_id;
                        $adminUser->phone            = $phone;
                        $adminUser->business_hall_id = $business_hall_id;
                        if ($adminUser->save() && $role) {
                            //添加成功之后添加角色
                            $adminUser->roles()->sync([$role]);
                        }
                        //成功的行数
                        $successCount++;
                    }
                }
                //组合记录导入日志数据
                $history['batch'] = $batch;
                $history['count'] = $num;
            });

            $allErrorRows           = [];
            $allErrorRows           = array_unique(array_merge($errorRow['name_empty'], $errorRow['name_unique'], $errorRow['real_name_empty'], $errorRow['password_empty'], $errorRow['area_empty'], $errorRow['area_validity'], $errorRow['phone_empty'], $errorRow['phone_unique'], $errorRow['business_hall_empty'], $errorRow['business_hall_validity'], $errorRow['role_empty'], $errorRow['role_validity']));
            $errorCount             = count($allErrorRows);
            $history['error_count'] = $errorCount;
            $history['file_url']    = $file_url;
            $history['user_id']     = $user_id;
            // $history['created_at']    = date('Y-m-d H:i:s');
            $history['success_count'] = $successCount;
            //导入结束时间
            $endtime                   = microtime(true);
            $consuming_time            = round($endtime - $starttime, 4);
            $history['consuming_time'] = $consuming_time;
            // 写批量导入用户的日志表
            // DB::table('bath_import_user_historys')->insert($history);
            BatchImportUserHistory::create($history);

            $flag    = true;
            $message = '<div style="word-wrap: break-word;">';
            $message .= '数据总数:';
            $message .= $history['count'] . '行<br />';
            $message .= '成功的行数:';
            $message .= $successCount . '行<br />';
            $message .= '错误的总行数:';
            $message .= $errorCount . '行<br />';

            if (count($errorRow['name_empty']) > 0) {
                $flag = false;
                $message .= '账号(name)为空的行号:' . implode(',', $errorRow['name_empty']) . '<br />';
            }
            if (count($errorRow['name_unique']) > 0) {
                $flag = false;
                $message .= '账号(name)不唯一的行号:' . implode(',', $errorRow['name_unique']) . '<br />';
            }
            if (count($errorRow['real_name_empty']) > 0) {
                $flag = false;
                $message .= '真实姓名(real_name)为空的行号:' . implode(',', $errorRow['real_name_empty']) . '<br />';
            }
            if (count($errorRow['password_empty']) > 0) {
                $flag = false;
                $message .= '密码(password)为空的行号:' . implode(',', $errorRow['password_empty']) . '<br />';
            }
            if (count($errorRow['area_empty']) > 0) {
                $flag = false;
                $message .= '地区(cityname, cells)为空的行号:' . implode(',', $errorRow['area_empty']) . '<br />';
            }
            if (count($errorRow['area_validity']) > 0) {
                $flag = false;
                $message .= '地区(cityname, cells)不合法的行号:' . implode(',', $errorRow['area_validity']) . '<br />';
            }
            if (count($errorRow['phone_empty']) > 0) {
                $flag = false;
                $message .= '手机号(phone)为空的行号:' . implode(',', $errorRow['phone_empty']) . '<br />';
            }
            if (count($errorRow['phone_unique']) > 0) {
                $flag = false;
                $message .= '手机号(phone)不唯一的行号:' . implode(',', $errorRow['phone_unique']) . '<br />';
            }
            if (count($errorRow['business_hall_empty']) > 0) {
                $flag = false;
                $message .= '营业厅(restore)为空的行号:' . implode(',', $errorRow['business_hall_empty']) . '<br />';
            }
            if (count($errorRow['business_hall_validity']) > 0) {
                $flag = false;
                $message .= '营业厅(restore)不合法的行号:' . implode(',', $errorRow['business_hall_validity']) . '<br />';
            }
            if (count($errorRow['role_empty']) > 0) {
                $flag = false;
                $message .= '角色(role)为空的行号:' . implode(',', $errorRow['role_empty']) . '<br />';
            }
            if (count($errorRow['role_validity']) > 0) {
                $flag = false;
                $message .= '角色(role)不合法的行号:' . implode(',', $errorRow['role_validity']) . '<br />';
            }
            $message .= '</div>';

            //通过标志位判断前端返回时成功还是失败
            if ($flag) {
                Flash::success($message);
            } else {
                Flash::error($message);
            }
            return back()->withInput();
        }
        Flash::error('文件上传失败');
        return back()->withInput(); //关联持久用户提交的信息
    }

    protected function form()
    {
        return Admin::form(AdminUser::class, function (Form $form) {

            $form->model()->makeVisible('password');

            $form->tab('基本信息', function (Form $form) {
                $form->display('id', 'ID');
                $form->text('name', '用户名');
                $form->text('real_name', '真实姓名');
                $form->mobile('phone', '手机号');
                // $form->email('email', '邮箱');//现在邮箱不是必须
                $form->text('wxno', '微信openid');

                //地区
                $arrAreas = Area::visualRegion()->orderBy('listorder', 'asc')->get(['f_id', 'f_pid', 'alias'])->toArray();
                $form->ztree('area_id', '地区')->zTreeConfig(["map" => ["f_id" => "id", "alias" => 'name', "f_pid" => "pId"], "type" => "radio", "open" => true])->options($arrAreas);

                //营业厅
                $arrBusinessHalls = BusinessHall::visualBusinessHalls()->orderBy('listorder', 'asc')->pluck('name', 'id')->toArray();
                $form->select('business_hall_id', "营业厅")->options(["NULL" => "空"] + $arrBusinessHalls);

                //$form->image('photo', "图像")

                $form->display('created_at', __('inventory.created_at'));
                $form->display('updated_at', __('inventory.updated_at'));

            })->tab('密码', function (Form $form) {
                $form->password('password', '密码')->rules('confirmed');
                $form->password('password_confirmation', '确认密码');

            });
            $form->ignore(['password_confirmation']);
        });
    }

    protected function grid()
    {
        $route_prefix = $this->route_prefix;
        return Admin::grid(AdminUser::class, function (Grid $grid) use ($route_prefix) {
            //数据范围限制 - 通过地区限制
            $grid->model()->visualRegion()->where(function ($query) {
                //如果有营业厅的属性,则限制到营业厅这个级别
                if (!empty(auth()->user()->business_hall_id)) {
                    $query = $query->where('admin_users.business_hall_id', '=', auth()->user()->business_hall_id);
                }
                return $query;
            });

            //添加按钮
            if (!\Gate::check('admin.user.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                //编辑按钮
                if (!\Gate::check('admin.user.edit')) {
                    $actions->disableEdit();
                }
                //删除按钮
                if (!\Gate::check('admin.user.destroy')) {
                    $actions->disableDelete();
                }
            });

            //导出按钮
            if (!\Gate::check('admin.user.export')) {
                $grid->disableExport();
            }

            //批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    //批量删除按钮
                    if (!\Gate::check('admin.user.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            // 批量导入
            if (\Gate::check('admin.user.batchImportView')) {
                $grid->tools(function ($tools) use ($route_prefix) {
                    $tools->append('<a href="' . route($route_prefix . '.user.batchImportView') . '" class="btn btn-sm btn-danger pull-right" style="margin-right: 10px"><i class="fa fa-bars"></i>批量导入</a>');
                });
            }

            //表格中的按钮
            $grid->actions(function ($actions) use ($route_prefix) {
                //如果是超级管理员, 则权限删除它
                if ($actions->row->level == 1) {
                    $actions->disableDelete();
                }
                //如果是超级管理员, 并且是自己则没有权限编辑它
                if ($actions->row->level == 1 && $actions->row->id != Auth::guard(config('inventory.base.guard'))->user()->id) {
                    $actions->disableEdit();
                }
                //如果是自己也没有权限删除
                if ($actions->row->id == Auth::guard(config('inventory.base.guard'))->user()->id) {
                    $actions->disableDelete();
                }
                //如果不是超级管理员 并且不是自己 则可以给他分配权限
                if ($actions->row->level != 1 && ($actions->row->id != Auth::guard(config('inventory.base.guard'))->user()->id)) {
                    $actions->prepend('<a href="' . route($route_prefix . '.user.distributionView', $actions->getKey()) . '"><i class="fa fa-angellist"></i></a>');
                }
            });

            /**
             * 表格中的字段
             */
            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '用户名')->sortable();
            $grid->column('real_name', '真实姓名')->sortable();
            $grid->column('phone', '手机号');
            $grid->column('wxno', '微信openid');
            // $grid->column('email', '邮箱');
            //角色
            $grid->roles('角色')->pluck('name')->label();
            //地区
            $grid->column('area.alias', '地区')->sortable();
            //营业厅
            $grid->column('businessHall.name', '营业厅')->sortable();
            // $grid->column('created_at', __('inventory.created_at'))->sortable();
            // $grid->column('updated_at', __('inventory.updated_at'))->sortable();

            /**
             * 表格过滤区域
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                $filter->disableIdFilter();
                $filter->like('id', '用户ID');
                $filter->like('name', '用户名');
                $filter->like('real_name', '真实姓名');
                $filter->like('phone', '手机号');
                //地区
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->where('area_id', '=', "{$this->input}")
                        ->orWhere('area_id', 'like', "{$this->input}.%");
                }, '地区')->select(Area::visualRegion()->pluck('alias', 'f_id'));

                //营业厅 - 当前角色可见的营业厅
                $tempBusinessHalls = BusinessHall::visualBusinessHalls()->pluck('name', 'id');
                $filter->is('business_hall_id', '营业厅')->select($tempBusinessHalls);
            });
        });
    }

    /**
     * 批量用户导入的form
     */
    protected function batchImportForm()
    {
        // 文件
        return Admin::form(AdminUser::class, function (Form $form) {
            //设置表单提交的action
            $form->setAction(route('admin.user.batchImport')); //admin/users/batchImport
            // 编辑界面的按钮
            $form->tools(function (Form\Tools $tools) {
                // 去掉返回按钮
                // $tools->disableBackButton();
                // 去掉跳转列表按钮
                $tools->disableListButton();
                // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
                //$tools->add('<a class="btn btn-sm btn-danger"><i class="fa fa-trash"></i>&nbsp;&nbsp;delete</a>');
            });

            $form->file('file', '文件');
        });
    }
}
